package com.wk.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter(){
        // 初始化CORS跨域配置对象
        CorsConfiguration config = new CorsConfiguration();

        // 允许访问项目的域,如果需要携带cookie就不能写"*"
        config.addAllowedOrigin("http://localhost:1000");
        config.addAllowedOrigin("http://127.0.0.1:1000");

        // 允许的头信息
        config.addAllowedHeader("*");

        // 允许的请求方式
        config.addAllowedMethod("*");

        // 是否允许携带Cookie信息
        config.setAllowCredentials(true);

        // 添加映射路径，拦截所有请求
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);

        //cross过滤器对象
        return new CorsWebFilter(corsConfigurationSource);
    }

}
